package cn.bdqn.t354.controller;

import cn.bdqn.t354.config.shiro.MyShiroRealm;
import cn.bdqn.t354.pojo.Right;
import cn.bdqn.t354.pojo.Role;
import cn.bdqn.t354.pojo.User;
import cn.bdqn.t354.service.RightService;
import cn.bdqn.t354.service.UserService;
import cn.bdqn.t354.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Resource
    UserService userService;
    @Resource
    RightService rightService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 跳转主页面
     * @return
     */
    @RequestMapping("/main")
    public String main(){
        return "main";
    }

    /**
     * 跳转403页面
     * @return
     */
    @RequestMapping("/403")
    public String authorization(){
        return "403";
    }

    @RequestMapping("/dologin")
    public String dologin(String usrName, String usrPassword, boolean rememberme,
                          HttpSession session, Model model){
//        User user = userService.login(usrName, usrPassword);
//        if(user!=null){
//            session.setAttribute("loginUser",user);
//            return "redirect:/main";
//        }else{
//            model.addAttribute("msg","用户名或者密码错误");
//            return "forward:/login";
//        }

//        usrPassword= MD5Utils.encryPassword(usrPassword);
        UsernamePasswordToken token=
                new UsernamePasswordToken(usrName,usrPassword, rememberme);
        Subject subject= SecurityUtils.getSubject();
        try {
            subject.login(token);
            //登录成功
            //清空密码错误次数计数器
            stringRedisTemplate.delete("shiro_login_count_"+usrName);

            User user=(User)subject.getPrincipal();
            System.out.println("猫的SESSION："+session.getId());
            System.out.println("shiro的SESSION："+subject.getSession().getId());

            //查询出该用户所有的权限
            Role role = user.getRole();
            List<Right> rights=rightService.findRightsByRoleId(role.getRoleId());
            role.getRights().addAll(rights);

            //刷新当前用户的权限缓存
            RealmSecurityManager securityManager =
                    (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm myShiroRealm =
                    (MyShiroRealm)securityManager.getRealms().iterator().next();
            myShiroRealm.clearMyAuthenticationInfoCache();

            session.setAttribute("loginUser",user);
            return "redirect:/main";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg",e.getMessage());
            return "forward:/login";
        }catch (LockedAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg",e.getMessage());
            return "forward:/login";
        }catch (DisabledAccountException e){
            e.printStackTrace();
            model.addAttribute("msg",e.getMessage());
            return "forward:/login";
        }catch (AuthenticationException e) {
            e.printStackTrace();
            model.addAttribute("msg",e.getMessage());
            return "forward:/login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "forward:/login";
    }
}
